package br.skytef.stmanager.beans;

import java.io.IOException;
import java.sql.SQLException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import jxl.read.biff.BiffException;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

import br.skytef.stmanager.daos.ControlPlanilhaDAO;
import br.skytef.stmanager.entities.ControlPlanilhasEntity;
import br.skytef.stmanager.entities.UsuarioEntity;
import br.skytef.stmanager.utils.ImportandoDados;
import br.skytef.stmanager.utils.PlanCliente;
import br.skytef.stmanager.utils.PlanFinanceiro;

@ManagedBean(name="ClienteBean")
@SessionScoped
public class ClienteBean {

	private static PlanCliente planilha;
	public static synchronized PlanCliente getPlanilha() {return planilha;}
	public static synchronized void setPlanilha(PlanCliente planilha) {ClienteBean.planilha = planilha;}

	private static PlanFinanceiro planilha2;
	public static synchronized PlanFinanceiro getPlanilha2() {return planilha2;}
	public static synchronized void setPlanilha2(PlanFinanceiro planilha2) {ClienteBean.planilha2 = planilha2;}

	private static String fileNameUploaded;
	public static synchronized String getFileNameUploaded() {return fileNameUploaded;}
	public static synchronized void setFileNameUploaded(String fileNameUploaded) {ClienteBean.fileNameUploaded = fileNameUploaded;}
	private ControlPlanilhasEntity cp;
	private HttpSession session;
	private UsuarioEntity usuario;

	public ClienteBean(){
		FacesContext ctx = FacesContext.getCurrentInstance();
		session = (HttpSession) ctx.getExternalContext().getSession(false);
		usuario = (UsuarioEntity)session.getAttribute("usuario");
		if(usuario == null)
			new LoginBean().encerraSessao();
	}

	/**
	 * Método para importação das planilhas.
	 * @param fileUploadEvent
	 * @throws IOException
	 * @throws BiffException
	 * @throws SQLException 
	 */

	public void doUpload (FileUploadEvent fileUploadEvent) throws BiffException, IOException, InterruptedException, SQLException{
		UploadedFile uploadedFile = fileUploadEvent.getFile();
		fileNameUploaded = uploadedFile.getFileName();
		int ult = fileNameUploaded.length()-1;
		if(fileNameUploaded.charAt(ult) =='s' &&
				fileNameUploaded.charAt(ult-1) =='l' &&
				fileNameUploaded.charAt(ult-2) =='x' &&
				fileNameUploaded.charAt(ult-3) =='.'){

			planilha = new PlanCliente(uploadedFile.getInputstream());
			planilha2 = new PlanFinanceiro(uploadedFile.getInputstream());
			if (planilha.validar()){
				ImportandoDados inserir= new ImportandoDados();
				inserir.setPlanilha(planilha);
				inserir.setPlanilha2(null);
				inserir.setNomePlanilha(fileNameUploaded);
				inserir.setUsuario(usuario);
				Thread t1 = new Thread(inserir);
				t1.start();
				t1.join();
				cp = new ControlPlanilhaDAO().buscar(1);
				String infoAboutFile = "<br/> Arquivo recebido: <b>"+fileNameUploaded +"</b><br/>";
				if (cp.getErros()!= 0){

					FacesContext facesContext = FacesContext.getCurrentInstance(); 
					facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Importação realizada com sucesso,porém com erros", infoAboutFile));
				}
				if (cp.getErros() == 0){
					FacesContext facesContext = FacesContext.getCurrentInstance(); 
					facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Importação realizada com sucesso ", infoAboutFile));

				}

			}else if(planilha2.validar()){
				ImportandoDados inserir2= new ImportandoDados();
				inserir2.setPlanilha2(planilha2);
				inserir2.setPlanilha(null);
				inserir2.setNomePlanilha(fileNameUploaded);
				inserir2.setUsuario(usuario);
				Thread t2 = new Thread(inserir2);
				t2.start();
				t2.join();
				cp = new ControlPlanilhaDAO().buscar(2);
				String infoAboutFile = "<br/> Arquivo recebido: <b>"+fileNameUploaded +"</b><br/>";
				if (cp.getErros()!= 0){

					FacesContext facesContext = FacesContext.getCurrentInstance(); 
					facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Importação realizada com sucesso,porém com erros", infoAboutFile));
				}
				if (cp.getErros() == 0){
					FacesContext facesContext = FacesContext.getCurrentInstance(); 
					facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Importação realizada com sucesso ", infoAboutFile));

				}

			}

		}else{
			FacesContext facesContext = FacesContext.getCurrentInstance(); 
			facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Falha", "Formato de arquivo inválido"));
		}
	}

}
